package facebooksharing;

import facebook4j.FacebookException;
import facebook4j.Group;
import facebook4j.internal.org.json.JSONException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Janela extends javax.swing.JFrame {

    Set<String> forbiddenGroups = new HashSet<String>();
    Set<String> forbiddenPages = new HashSet<String>();
    private File selectedFile;
    private File forbiddenGroupsFile = new File("forbiddenGroups.txt");
    private File forbiddenPagesFile = new File("forbiddenPages.txt");
    final int TIME = 5000;

    public Janela() {
        initComponents();
        setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
        MyCellGroupRenderer cellGroupRenderer = new MyCellGroupRenderer();
        groupList.setCellRenderer(cellGroupRenderer);
        MyCellPageRenderer cellPageRenderer = new MyCellPageRenderer();
        pageList.setCellRenderer(cellPageRenderer);
        setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        accessTokenText = new javax.swing.JTextField();
        accessButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        imageTxt = new javax.swing.JTextField();
        imageButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        msgTxtPhotoTab = new javax.swing.JTextArea();
        sendButtonPhotoTab = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        msgTxtTextTab = new javax.swing.JTextArea();
        sendButtonTextTab = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        linkTxt = new javax.swing.JTextField();
        jScrollPane5 = new javax.swing.JScrollPane();
        msgTxtLinkTab = new javax.swing.JTextArea();
        jLabel8 = new javax.swing.JLabel();
        sendButtonLinkTab = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        groupList = new javax.swing.JList();
        forbiddenGroupsButton = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        pageList = new javax.swing.JList();
        jLabel6 = new javax.swing.JLabel();
        forbiddenPagesButton = new javax.swing.JButton();
        pagesCounter = new javax.swing.JTextField();
        groupsCounter = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Access Token:");

        accessButton.setText("Acessar");
        accessButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                accessButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("Imagem");

        imageTxt.setEditable(false);
        imageTxt.setBackground(java.awt.Color.white);
        imageTxt.setEnabled(false);

        imageButton.setText("Abrir");
        imageButton.setEnabled(false);
        imageButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                imageButtonActionPerformed(evt);
            }
        });

        jLabel3.setText("Mensagem");

        msgTxtPhotoTab.setColumns(20);
        msgTxtPhotoTab.setRows(5);
        msgTxtPhotoTab.setEnabled(false);
        jScrollPane2.setViewportView(msgTxtPhotoTab);

        sendButtonPhotoTab.setText("Enviar");
        sendButtonPhotoTab.setEnabled(false);
        sendButtonPhotoTab.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonPhotoTabActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(imageTxt)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(imageButton))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)
                        .addGap(160, 160, 160)
                        .addComponent(sendButtonPhotoTab)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(imageTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(imageButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sendButtonPhotoTab)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Foto", jPanel1);

        jLabel5.setText("Mensagem");

        msgTxtTextTab.setColumns(20);
        msgTxtTextTab.setRows(5);
        msgTxtTextTab.setEnabled(false);
        jScrollPane1.setViewportView(msgTxtTextTab);

        sendButtonTextTab.setText("Enviar");
        sendButtonTextTab.setEnabled(false);
        sendButtonTextTab.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonTextTabActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(sendButtonTextTab))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sendButtonTextTab)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Texto", jPanel2);

        jLabel7.setText("Link");

        linkTxt.setEnabled(false);

        msgTxtLinkTab.setColumns(20);
        msgTxtLinkTab.setRows(5);
        msgTxtLinkTab.setEnabled(false);
        jScrollPane5.setViewportView(msgTxtLinkTab);

        jLabel8.setText("Mensagem");

        sendButtonLinkTab.setText("Enviar");
        sendButtonLinkTab.setEnabled(false);
        sendButtonLinkTab.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonLinkTabActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane5)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(linkTxt)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)
                        .addGap(210, 210, 210))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(sendButtonLinkTab)))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(linkTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sendButtonLinkTab)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Link", jPanel3);

        groupList.setEnabled(false);
        jScrollPane3.setViewportView(groupList);

        forbiddenGroupsButton.setText("Proibir");
        forbiddenGroupsButton.setEnabled(false);
        forbiddenGroupsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                forbiddenGroupsButtonActionPerformed(evt);
            }
        });

        jLabel4.setText("Páginas");

        pageList.setEnabled(false);
        jScrollPane4.setViewportView(pageList);

        jLabel6.setText("Grupos");

        forbiddenPagesButton.setText("Proibir");
        forbiddenPagesButton.setEnabled(false);
        forbiddenPagesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                forbiddenPagesButtonActionPerformed(evt);
            }
        });

        pagesCounter.setEditable(false);

        groupsCounter.setEditable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(accessTokenText)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(accessButton)
                        .addGap(18, 18, 18))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(forbiddenPagesButton)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(pagesCounter)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(forbiddenGroupsButton)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(groupsCounter)))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTabbedPane1)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(accessTokenText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(accessButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTabbedPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane3)
                            .addComponent(jScrollPane4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(forbiddenGroupsButton)
                            .addComponent(forbiddenPagesButton)
                            .addComponent(pagesCounter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(groupsCounter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void readGroups() throws FacebookException {
        BufferedReader reader = null;
        try {
            forbiddenGroups.clear();
            FacebookSharing sharing = FacebookSharing.getInstance();
            reader = new BufferedReader(new FileReader(forbiddenGroupsFile));
            String line = reader.readLine();
            while (line != null) {
                if (!line.isEmpty()) {
                    forbiddenGroups.add(line);
                }

                line = reader.readLine();
            }
            reader.close();
            DefaultListModel<Group> listModel = new DefaultListModel<Group>();
            List<Group> result = sharing.getGroups();

            Collections.sort(result, new Comparator<Group>() {
                @Override
                public int compare(Group o1, Group o2) {
                    return o1.getName().compareToIgnoreCase(o2.getName());
                }
            });

            int counter = 0;
            for (Group group : result) {
                if (!forbiddenGroups.contains(group.getId())) {
                    counter++;
                    listModel.addElement(group);
                }
            }

            groupList.setModel(listModel);
            int[] indices = new int[counter];
            for (int index = 0; index < counter; index++) {
                indices[index] = index;
            }
            groupList.setSelectedIndices(indices);
            groupsCounter.setText(String.valueOf(counter));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void readPages() throws FacebookException {
        BufferedReader reader = null;
        try {
            forbiddenPages.clear();
            FacebookSharing sharing = FacebookSharing.getInstance();
            reader = new BufferedReader(new FileReader(forbiddenPagesFile));
            String line = reader.readLine();
            while (line != null) {
                if (!line.isEmpty()) {
                    forbiddenPages.add(line);
                }

                line = reader.readLine();
            }
            reader.close();
            DefaultListModel<Page> listModel = new DefaultListModel<Page>();
            List<Page> result = sharing.getPages();

            Collections.sort(result, new Comparator<Page>() {
                @Override
                public int compare(Page o1, Page o2) {
                    return o1.getName().compareToIgnoreCase(o2.getName());
                }
            });

            int counter = 0;
            for (Page page : result) {
                if (!forbiddenPages.contains(page.getId())) {
                    counter++;
                    listModel.addElement(page);
                }
            }

            pageList.setModel(listModel);
            int[] indices = new int[counter];
            for (int index = 0; index < counter; index++) {
                indices[index] = index;
            }
            pageList.setSelectedIndices(indices);
            pagesCounter.setText(String.valueOf(counter));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JSONException ex) {
            Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void setEnabledOfAll(boolean enabled) {
        imageButton.setEnabled(enabled);
        imageTxt.setEnabled(enabled);
        groupList.setEnabled(enabled);
        pageList.setEnabled(enabled);
        msgTxtPhotoTab.setEnabled(enabled);
        sendButtonPhotoTab.setEnabled(enabled);
        forbiddenGroupsButton.setEnabled(enabled);
        forbiddenPagesButton.setEnabled(enabled);
        sendButtonTextTab.setEnabled(enabled);
        msgTxtTextTab.setEnabled(enabled);
        linkTxt.setEnabled(enabled);
        msgTxtLinkTab.setEnabled(enabled);
        sendButtonLinkTab.setEnabled(enabled);
    }

    private void accessButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_accessButtonActionPerformed
        String accessToken = accessTokenText.getText();
        if (accessToken != null && !accessToken.isEmpty()) {
            try {
                FacebookSharing sharing = FacebookSharing.getInstance();
                sharing.setAccessToken(accessToken);
                setEnabledOfAll(true);
                readGroups();
                readPages();
            } catch (FacebookException exception) {
                setEnabledOfAll(false);
                if (exception.getMessage().contains("Error validating access token: Session has expired")) {
                    JOptionPane.showMessageDialog(null, "Access Token Expirado!");
                } else {
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, exception);
                }
            }
        }
    }//GEN-LAST:event_accessButtonActionPerformed

    private void forbiddenGroupsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_forbiddenGroupsButtonActionPerformed
        try {
            List<Group> groups = groupList.getSelectedValuesList();

            if (!groups.isEmpty()) {
                for (Group group : groups) {
                    forbiddenGroups.add(group.getId());
                }

                BufferedWriter writer = new BufferedWriter(new FileWriter(forbiddenGroupsFile));
                for (String groupId : forbiddenGroups) {
                    if (!groupId.isEmpty()) {
                        writer.write(groupId);
                        writer.newLine();
                    }
                }
                writer.close();

                readGroups();
            }
        } catch (Exception ex) {
            Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_forbiddenGroupsButtonActionPerformed

    private void sendButtonPhotoTabActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonPhotoTabActionPerformed
        List<Group> groups = groupList.getSelectedValuesList();
        List<Page> pages = pageList.getSelectedValuesList();

        String message = msgTxtPhotoTab.getText();

        if ((!groups.isEmpty() || !pages.isEmpty()) && selectedFile != null && message != null && !message.isEmpty()) {
            FacebookSharing sharing = FacebookSharing.getInstance();
            for (Group object : groups) {
                try {
                    sharing.postPhoto(object, selectedFile, message);
                    System.out.println("Divulgação enviada para grupo: " + object.getName() + " - " + object.getId());
                } catch (Exception exception) {
                    System.out.println("Falha no envio da divulgação para página: " + object.getName() + " - " + object.getId());
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, exception);
                }
                try {
                    Thread.sleep(TIME);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            for (Page object : pages) {
                try {
                    sharing.postPhoto(object, selectedFile, message);
                    System.out.println("Divulgação enviada para página: " + object.getName() + " - " + object.getId());
                } catch (Exception exception) {
                    System.out.println("Falha no envio da divulgação para página: " + object.getName() + " - " + object.getId());
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, exception);
                }
                try {
                    Thread.sleep(TIME);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            JOptionPane.showMessageDialog(null, "Divulgação finalizada!");
        }
    }//GEN-LAST:event_sendButtonPhotoTabActionPerformed

    private void imageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_imageButtonActionPerformed
        final JFileChooser fc = new JFileChooser();
        fc.setFileFilter(new MyFileFilter());
        fc.setAcceptAllFileFilterUsed(false);

        int returnVal = fc.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            selectedFile = fc.getSelectedFile();
            imageTxt.setText(selectedFile.getAbsolutePath());
        } else {
            selectedFile = null;
            imageTxt.setText(null);
        }
    }//GEN-LAST:event_imageButtonActionPerformed

    private void sendButtonTextTabActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonTextTabActionPerformed
        List<Group> groups = groupList.getSelectedValuesList();
        List<Page> pages = pageList.getSelectedValuesList();

        String message = msgTxtTextTab.getText();

        if ((!groups.isEmpty() || !pages.isEmpty()) && message != null && !message.isEmpty()) {

            FacebookSharing sharing = FacebookSharing.getInstance();
            for (Group object : groups) {
                try {
                    sharing.postText(object, message);
                    System.out.println("Divulgação enviada para grupo: " + object.getName() + " - " + object.getId());
                } catch (Exception exception) {
                    System.out.println("Falha no envio da divulgação para página: " + object.getName() + " - " + object.getId());
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, exception);
                }
                try {
                    Thread.sleep(TIME);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            for (Page object : pages) {
                try {
                    sharing.postText(object, message);
                    System.out.println("Divulgação enviada para página: " + object.getName() + " - " + object.getId());
                } catch (Exception exception) {
                    System.out.println("Falha no envio da divulgação para página: " + object.getName() + " - " + object.getId());
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, exception);
                }
                try {
                    Thread.sleep(TIME);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            JOptionPane.showMessageDialog(null, "Divulgação finalizada!");
        }
    }//GEN-LAST:event_sendButtonTextTabActionPerformed

    private void forbiddenPagesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_forbiddenPagesButtonActionPerformed
        try {
            List<Page> pages = pageList.getSelectedValuesList();

            if (!pages.isEmpty()) {
                for (Page page : pages) {
                    forbiddenPages.add(page.getId());
                }

                BufferedWriter writer = new BufferedWriter(new FileWriter(forbiddenPagesFile));
                for (String pageId : forbiddenPages) {
                    if (!pageId.isEmpty()) {
                        writer.write(pageId);
                        writer.newLine();
                    }
                }
                writer.close();

                readPages();
            }
        } catch (Exception ex) {
            Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_forbiddenPagesButtonActionPerformed

    private void sendButtonLinkTabActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonLinkTabActionPerformed
        List<Group> groups = groupList.getSelectedValuesList();
        List<Page> pages = pageList.getSelectedValuesList();

        String link = linkTxt.getText();
        String message = msgTxtLinkTab.getText();

        if ((!groups.isEmpty() || !pages.isEmpty()) && message != null && !message.isEmpty() && link != null && !link.isEmpty()) {

            FacebookSharing sharing = FacebookSharing.getInstance();
            for (Group object : groups) {
                try {
                    sharing.postLink(object, link, message);
                    System.out.println("Divulgação enviada para grupo: " + object.getName() + " - " + object.getId());
                } catch (Exception exception) {
                    System.out.println("Falha no envio da divulgação para grupo: " + object.getName() + " - " + object.getId());
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, exception);
                }
                try {
                    Thread.sleep(TIME);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            for (Page object : pages) {
                try {
                    sharing.postLink(object, link, message);
                    System.out.println("Divulgação enviada para página: " + object.getName() + " - " + object.getId());
                } catch (Exception exception) {
                    System.out.println("Falha no envio da divulgação para página: " + object.getName() + " - " + object.getId());
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, exception);
                }
                try {
                    Thread.sleep(TIME);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Janela.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            JOptionPane.showMessageDialog(null, "Divulgação finalizada!");
        }
    }//GEN-LAST:event_sendButtonLinkTabActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton accessButton;
    private javax.swing.JTextField accessTokenText;
    private javax.swing.JButton forbiddenGroupsButton;
    private javax.swing.JButton forbiddenPagesButton;
    private javax.swing.JList groupList;
    private javax.swing.JTextField groupsCounter;
    private javax.swing.JButton imageButton;
    private javax.swing.JTextField imageTxt;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextField linkTxt;
    private javax.swing.JTextArea msgTxtLinkTab;
    private javax.swing.JTextArea msgTxtPhotoTab;
    private javax.swing.JTextArea msgTxtTextTab;
    private javax.swing.JList pageList;
    private javax.swing.JTextField pagesCounter;
    private javax.swing.JButton sendButtonLinkTab;
    private javax.swing.JButton sendButtonPhotoTab;
    private javax.swing.JButton sendButtonTextTab;
    // End of variables declaration//GEN-END:variables
}
